<?php
    namespace CKB\Controller;
    use Think\Controller;
    class IndexController extends Controller {
        public function index(){
            $this->loadtree();
            
            if(!$this->is_login()){
                echo '<meta charset="utf-8">';
                redirect(U('Home/Login/index'),1,'请登录后使用,正在为你跳转！');
            }else{
                $this->display();
            }
        }
        public function loadtree(){
            $tree = D('Tree');
            $condition['PID'] = 0;
            $data = $tree->where($condition)->select();
            //检查获得的数据行中是否存在子项，有则从getchildren中获取子项并加入
            foreach ($data as $key => $value){
                $data[$key]['children']=$this->getchildren($value['ID']);
            }
            $hd  = fopen('./Public/Tree/tree_data1.json', 'w');
            $jsonr = json_encode($data);
            if(!fwrite($hd, $jsonr)){
                $this->error('初始化路径表失败');
            }
            fclose($hd);

        }
        public function getchildren($id = 0){
            $model = D('Tree');
            $condition['PID'] = $id;
            $data = $model->where($condition)->select();
            foreach ($data as $key => $value){
                $data[$key]['children']=$this->getchildren($value['ID']);
            }
            return $data;
        }
        public function read($address){
            $url = './Application/CKB/View/Kb/'.$address.'.html';
            $url = str_replace(':','/',$url);
            $html = file_get_contents($url);
            if(!$html){
                echo '载入资源失败，资源文件可能已被删除或冻结。';
            }else{
                echo $html;  
            }
        }
        public function is_login(){
            $UserID = session('uid');
            if(empty($UserID)){
                return false;
            }else{
                return true;
            }
        }
}